package com.wk.sc.sz.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 自定义zuul过滤规则
 *
 * @author zhang peng
 * @since 2019/4/9 14:05
 */
@Component
public class MyFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

    /**
     * 定义过滤周期类型
     * 在zuul中定义了4中过滤周期类型：
     * pre：路由前
     * routing：路由时
     * post：路由后
     * error：发生错误时调用
     *
     * @return
     */
    @Override
    public String filterType() {

        return "pre";
    }

    /**
     * 过滤顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 根据条件定义是否需要过滤：
     * true：需要过滤
     * false：不需要
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //需要过滤生效，此处需要返回true
        return true;
    }

    /**
     * 过滤器具体实现，可以结合业务需求进行复杂的实现
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        logger.info("请求信息,方法[{}],URL[{}]", request.getMethod(), request.getRequestURL().toString());
        //模拟token校验
        String token = request.getParameter("token");
        if (token == null || token.length() == 0){
            //token校验失败返回401
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            try {
                requestContext.getResponse().getWriter().write("token 为空");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            logger.info("校验通过");
        }
        return null;
    }
}
